import Vue from 'vue';
// 导入axios包
import axios from 'axios';
import router from '@/router';
import { Message } from 'element-ui';
import httpCode from './httpCode';

const service = axios.create({
  // 为axios设置请求的根路径
  baseURL: process.env.VUE_APP_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
});

// axios挂载到原型上之前，先设置请求拦截器，config是请求对象
service.interceptors.request.use((config) => {
  console.log(config);
  // return之前先对config进行预处理，为请求头对象添加Token验证的Authorization字段
  config.headers.Authorization = sessionStorage.getItem('token');
  // 在最后必须 return config
  return config;
});

// axios挂载到原型上之前，先设置请求拦截器，config是请求对象
service.interceptors.response.use(
  (response) => {
    console.log(response);
    // 若未返回状态码则默认设置失败状态
    const code = response.data.code || 'default';
    if (code === 200) {
      return response;
    } else {
      switch (code) {
        // 用户未登录/token无效
        case 401:
          router.replace({
            path: '/401',
          });
          break;
        case 404:
          router.replace({
            path: '/404',
          });
          break;

        default:
          break;
      }
      const msg = response.data.msg || httpCode[code];
      Message.error(msg);
      return Promise.reject(msg || 'error');
    }
  },
  (error) => {
    let msg = error.message;
    const code = error?.response?.status || 'default';
    if (msg == 'Network Error') {
      msg = '网络异常';
    } else if (msg.includes('timeout')) {
      msg = '请求超时，请重试';
    } else if (msg.includes('Request failed with status code')) {
      msg = error?.response?.data?.message || httpCode[code] || '系统接口' + msg.substr(msg.length - 3) + '异常';
    }
    Message.error(msg);
    return Promise.reject(msg);
  },
);

// 把axios包挂载到Vue的原型对象上
Vue.prototype.$http = service;
